<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>发送请求</button>
    <button>取消请求</button>

    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
    <script>
        // 接口: http://localhost:8090/delay-server
        //  定义一个用来保存取消请求函数的变量
        let cancelFn;
        const btns = document.querySelectorAll('button');
        btns[0].onclick = async () => {
            try {
                let response = await axios({
                    url: 'http://localhost:8090/delay-server',
                    cancelToken: new axios.CancelToken((cancel) => {
                        cancelFn = cancel;
                    })

                })

                console.log(response);
                alert(response.data);
            } catch (error) {
              if(axios.isCancel(error)){
                  alert('取消请求了');
              }else{
                alert(error.message);
              }
            }
        }

        btns[1].onclick = () => {
            if (cancelFn) {
                cancelFn();
            }
        }
    </script>
</body>

</html>